package com.micro.frog.gender.exception;

import com.alibaba.fastjson.JSON;
import com.micro.frog.core.common.Result;
import com.micro.frog.core.contants.Punctuations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常处理器
 *
 * @author ljh
 * @date 2018/11/09
 */
@Component
public class GenderExceptionHandler implements HandlerExceptionResolver {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler, Exception ex) {
        Result result = new Result();
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");

            if (ex instanceof GenderException) {
                result.setCode(((GenderException) ex).getCode() + Punctuations.BLANK);
                result.setMsg(ex.getMessage());
            } else if (ex instanceof DuplicateKeyException) {
                result = Result.fail("数据库中已存在该记录");
            } else {
                result = Result.fail();
            }

            //记录异常日志
            logger.error(ex.getMessage(), ex);

            String json = JSON.toJSONString(result);
            response.getWriter().print(json);
        } catch (Exception e) {
            logger.error("ExceptionHandler 异常处理失败", e);
        }
        return new ModelAndView();
    }
}
